package cn.sc.summer.mybatis.runner;

import cn.sc.summer.constant.mybatisplus.datasource.DataSourceConstant;
import cn.sc.summer.mybatis.runner.service.ApiService;
import cn.sc.summer.redis.util.NacosInstancesService;
import cn.sc.summer.redis.util.RedisHelper;
import cn.sc.summer.thread.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;

/**
 * 类名：api接口公用启动类
 *
 * @author a-xin
 * @date 2023/8/25 14:31
 */
@Slf4j
@Component
public class MybatisRunner implements CommandLineRunner, ApplicationListener<ContextClosedEvent> {

    @Resource
    private ThreadUtil threadUtil;

    @Resource
    private ApiService apiService;

    @Override
    public void run(String... args) {
        CompletableFuture<Void> apiFuture = CompletableFuture.runAsync(() -> apiService.apiScan(), threadUtil.THREAD_POOL());
        CompletableFuture.allOf(apiFuture).whenComplete((result, exception) -> {
            exception.printStackTrace();
            log.error(exception.getMessage());
            log.info("==> The api and tenant table has been cached!");
        });
    }

    @Override
    public void onApplicationEvent(@NonNull ContextClosedEvent event) {
        if (NacosInstancesService.isLastInstance()) {
            //删除读写分离数据库统计次数key
            RedisHelper.del(DataSourceConstant.READ_PREFIX, DataSourceConstant.WRITE_PREFIX);
        }
    }

}
